package org.example.datascreen.Realm;


import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.example.datascreen.eneity.User;
import org.example.datascreen.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class UserRealm extends AuthorizingRealm {
    @Autowired
    private UserRepository userRepository;

    /**认证**/
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String name = (String) authenticationToken.getPrincipal();
        String password = new String((char[]) authenticationToken.getCredentials());
        // 查询用户信息
        User user = userRepository.findByUsernameAndPassword(name, password);
        if (user == null) {
            throw new UnknownAccountException("账户不存在!");
        }
        if (!password.equals(user.getPassword())) {
            throw new UnknownAccountException("密码错误!");
        }
        return new SimpleAuthenticationInfo(authenticationToken.getPrincipal(), password, getName());

    }

    /**授权**/
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals){
        return null;
    }

}